package pulpfizz.pulp.body;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;

import org.jbox2d.dynamics.Body;

import pulpcore.image.CoreImage;

/**
 * An attempt at a class to nicely draw java.awt.Shape objects attached to a
 * BodySprite. Useful for when you've used the PolygonUtils methods to create a
 * Body from a java.awt.Shape object, but you'd like PulpFizz to draw your nice,
 * smooth shape instead of the true physical model.
 * 
 * @author Greg
 * 
 */
public class ShapeBodyDrawer implements BodyDrawer
{
	public Shape shape;
	Paint paint;
	Paint strokePaint;
	double strokeWeight;

	public ShapeBodyDrawer(Shape shape)
	{
		this.shape = shape;
		this.paint = Color.white;
		this.strokePaint = Color.red;
		this.strokeWeight = 1;
	}

	public void drawBody(PhysicsLayer physics, Body b, Graphics2D g2)
	{
		g2.setPaint(paint);
		g2.fill(shape);

		if (strokeWeight > 0)
		{
			float stroke = 1 / physics.scaling * (float) strokeWeight;
			g2.setStroke(new BasicStroke(stroke));
			g2.setPaint(strokePaint);
			g2.draw(shape);
		}
		
		paint = null;
		shape = null;
		strokePaint = null;
	}

	public static HashMap<String,BufferedImage> assetToImage = new HashMap<String,BufferedImage>();
	public void setTexture(String imageAsset, double scale, double dx, double dy)
	{
		if (assetToImage.containsKey(imageAsset))
		{
			setTexturePaint(assetToImage.get(imageAsset),scale,dx,dy);
			return;
		}
		
		
		CoreImage img = CoreImage.load(imageAsset);

		BufferedImage texture = Java2DBodySprite.getBufferedImageView(img);
		setTexturePaint(texture, scale, dx, dy);
		assetToImage.put(imageAsset,texture);
	}

	public void setTexturePaint(BufferedImage image, double scale, double dx, double dy)
	{
		Rectangle2D rect = shape.getBounds2D();
		rect.setRect(rect.getX() + dx, rect.getY() + dy, rect.getWidth() * scale, rect.getHeight() * scale);

		TexturePaint texture = new TexturePaint(image, rect);
		setPaint(texture);
	}

	public void noStroke()
	{
		setStrokePaint(null);
	}

	public void noFill()
	{
		setPaint(null);
	}

	public Shape getShape()
	{
		return shape;
	}

	public void setShape(Shape shape)
	{
		this.shape = shape;
	}

	public Paint getPaint()
	{
		return paint;
	}

	public void setPaint(Paint paint)
	{
		this.paint = paint;
	}

	public Paint getStrokePaint()
	{
		return strokePaint;
	}

	public void setStrokePaint(Paint strokePaint)
	{
		this.strokePaint = strokePaint;
	}

	public double getStrokeWeight()
	{
		return strokeWeight;
	}

	public void setStrokeWeight(double strokeWeight)
	{
		this.strokeWeight = strokeWeight;
	}

	public boolean needsRedraw()
	{
		return false;
	}

}
